package com.ruoyi.system.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.domain.RecordTable;
import com.ruoyi.system.mapper.RecordManageMapper;
import com.ruoyi.system.mapper.RecordTableMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.system.mapper.RecordPropMapper;
import com.ruoyi.system.domain.RecordProp;
import com.ruoyi.system.service.IRecordPropService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * 动态字段管理Service业务层处理
 *
 * @author admin
 * @date 2022-10-04
 */
@Service
public class RecordPropServiceImpl implements IRecordPropService {
    @Autowired
    private RecordPropMapper recordPropMapper;
    @Autowired
    private RecordManageMapper recordManageMapper;
    @Autowired
    private RecordTableMapper recordTableMapper;

    /**
     * 查询动态字段管理
     *
     * @param id 动态字段管理主键
     * @return 动态字段管理
     */
    @Override
    public RecordProp selectRecordPropById(Long id) {
        return recordPropMapper.selectRecordPropById(id);
    }

    /**
     * 查询动态字段管理列表
     *
     * @param recordProp 动态字段管理
     * @return 动态字段管理
     */
    @Override
    public List<RecordProp> selectRecordPropList(RecordProp recordProp) {
        return recordPropMapper.selectRecordPropList(recordProp);
    }

    /**
     * 查询动态字段管理列表 馆藏
     *
     * @param map 动态字段管理
     * @return 动态字段管理
     */
    @Override
    public List<RecordProp> selectRecordPropListBook(Map<String, Object> map) {
        return recordPropMapper.selectRecordPropListBook(map);
    }

    /**
     * 新增动态字段管理
     *
     * @param recordProp 动态字段管理
     * @return 结果
     */
    @Override
    @Transactional
    public int insertRecordProp(RecordProp recordProp) {
        recordProp.setCreateBy(SecurityUtils.getUsername());
        recordProp.setUserId(SecurityUtils.getUserId());
        recordProp.setCreateTime(DateUtils.getNowDate());
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            Map<String, Object> map = new HashMap<>();
            RecordTable recordTable = recordTableMapper.selectRecordTableById(recordProp.getTableId());
            if(recordTable == null){
                throw new ServiceException("该表不存在");
            }
            String tbName = recordTable.getTbName();
            String columnName = recordProp.getProp();
            String columnType = recordProp.getPropType();
            String comment = recordProp.getLabel();
            String sql = "alter table " + tbName +  " add column `" + columnName + "` " + columnType + " DEFAULT NULL COMMENT '"+ comment +"' " ;
            map.put("sql", sql);
            recordManageMapper.insertRecordManage(map);
            return recordPropMapper.insertRecordProp(recordProp);
        } catch (Exception e) {
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            e.printStackTrace();
            return 0;
        }
    }

    /**
     * 修改动态字段管理
     *
     * @param recordProp 动态字段管理
     * @return 结果
     */
    @Override
    public int updateRecordProp(RecordProp recordProp) {
        recordProp.setUpdateBy(SecurityUtils.getUsername());
        recordProp.setUpdateTime(DateUtils.getNowDate());
        return recordPropMapper.updateRecordProp(recordProp);
    }

    /**
     * 批量删除动态字段管理
     *
     * @param ids 需要删除的动态字段管理主键
     * @return 结果
     */
    @Override
    public int deleteRecordPropByIds(Long[] ids) {
        return recordPropMapper.deleteRecordPropByIds(ids);
    }

    /**
     * 删除动态字段管理信息
     *
     * @param id 动态字段管理主键
     * @return 结果
     */
    @Override
    @Transactional
    @DataScope(deptAlias = "d", userAlias = "u")
    public int deleteRecordPropById(Long id) {
        // 设置回滚点
        Object savePoint = TransactionAspectSupport.currentTransactionStatus().createSavepoint();
        try {
            RecordProp recordProp = recordPropMapper.selectRecordPropById(id);
            RecordTable recordTable = recordTableMapper.selectRecordTableById(recordProp.getTableId());
            if(recordProp == null || recordTable == null){
                throw new ServiceException("该表不存在");
            }
            String tbName = recordTable.getTbName();
            String columnName = recordProp.getProp();
            // 判断字段是否非空
            Map<String, Object> m = new HashMap<>();
            String s = "select count(a." + columnName + ") from " + tbName + " a"
                    + " left join sys_user u on a.userId = u.user_id"
                    + " left join sys_dept d on u.dept_id = d.dept_id";
            m.put("sql", s);
            Integer count = recordManageMapper.getCount(m);
            if(count > 0){
                throw new ServiceException("字段非空，禁止删除");
            }
            // 删除字段和维护记录
            String sql = "alter table " + tbName +  " drop " + columnName;
            Map<String, Object> map = new HashMap<>();
            map.put("sql", sql);
            recordManageMapper.updateRecordManage(map);
            return recordPropMapper.deleteRecordPropById(id);
        } catch (Exception e) {
            //手工回滚异常
            TransactionAspectSupport.currentTransactionStatus().rollbackToSavepoint(savePoint);
            e.printStackTrace();
            return 0;
        }
    }

}
